package com.agileai.portal.controller.sso;

import java.util.ArrayList;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.PickFillModelHandler;
import com.agileai.hotweb.domain.core.Resource;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.sso.SSOAppPickSelect;
import com.agileai.portal.bizmoduler.sso.UserSSOService;

public class SSOAppPickSelectListHandler extends PickFillModelHandler{
	public SSOAppPickSelectListHandler(){
		super();
		this.serviceId = buildServiceId(SSOAppPickSelect.class);
	}
	public ViewRenderer prepareDisplay(DataParam param){
		mergeParam(param);
		initParameters(param);
		this.setAttributes(param);
		
		User user = (User)getUser();
		List<DataRow> rsList = getService().queryPickFillRecords(param);
		List<DataRow> filtedRecords = new ArrayList<DataRow>();
		for (int i=0;i < rsList.size();i++){
			 DataRow row = rsList.get(i);
			 String appId = row.getString("APP_ID");
			 if (user.containResouce(Resource.Type.Application, appId)){
				 filtedRecords.add(row);
			 }
		}
		this.setRsList(filtedRecords);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
	protected SSOAppPickSelect getService() {
		return (SSOAppPickSelect)this.lookupService(this.getServiceId());
	}
	public ViewRenderer doAddSSOAppAction(DataParam param){
		String userId = param.get("userId");
		String appId = param.get("appId");
		UserSSOService userSSOService = this.lookupService(UserSSOService.class);
		userSSOService.addUserApplication(appId, userId);
		return new AjaxRenderer(SUCCESS);
	}
}